<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>
<body>

<div>
    <form onsubmit="return false">
    <textarea name="mes" style="width: 300px;height: 300px"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.mes.value)" />
    <textarea id="rallbackMes" style="width: 300px;height: 300px"></textarea>
     <input type="button" value="清空内容" onclick="document.getElementById('rallbackMes').value = ''">
    </form>
</div>
</body>
<script>
    //判断浏览器是否支持websocket
    var socket;
    if (window.WebSocket){
        socket = new WebSocket('ws:localhost:7000/send');
         //打开该来连接
        socket.onopen = function (ev) {

            document.getElementById('rallbackMes').value = '打开连接了~~~';
        }

        //关闭了该来连接
        socket.onclose = function (ev) {
            var rt = document.getElementById("rallbackMes");
            rt.value = rt.value + "\n" + "连接关闭了.."
        }

        //服务器推送数据到客户端
        socket.onmessage = function (ev) {
            alert(ev.data)
          var rt =   document.getElementById('rallbackMes');
          rt.value = rt.value + "\n" + ev.data;
        }

    }else{
        alert("该浏览器不支持websocket")
    }

    function send(message) {
        alert(message)
        //判断当前websocket
        if (!window.socket){
          return;
        }
        //是否打开状态
        alert(window.socket.readyState)
        if (window.socket.readyState == WebSocket.OPEN){

            socket.send(message);
        }

    }

</script>
</html>